package com.link.base.base.wechat.controller;

import com.link.base.base.accnt.model.Account;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.link.base.base.coupons.model.CollectRecord;
import com.link.base.base.coupons.service.CollectRecordService;
import com.link.base.base.wechat.service.ArticlesService;
import com.link.base.wechat.basic.util.WeixinHttpUtil;
import com.link.core.cllog.LCLogger;
import com.link.base.wechat.mpnews.model.Article;
import com.link.base.wechat.mpnews.service.ArticleService;
import com.link.base.wechat.wxplatform.model.WxPlatform;
import com.link.base.wechat.wxplatform.service.WxPlatformService;
import com.link.base.wechat.wxtoken.service.WxTokenService;
import com.link.core.basic.annotations.JsonParam;
import com.link.core.basic.controller.BasicController;
import com.link.core.basic.model.BasicModel;
import com.link.core.basic.query.QueryParams;
import com.link.core.basic.service.BasicService;
import com.link.core.util.StringUtils;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 1.图文素材，用于自定义创建的click事件以及群发图文。
 * 2.卡卷的创建
 *
 * @author lujiang
 * @date 2018-05
 */
@Controller
@RequestMapping("/link/articles")
public class ArticlesController extends BasicController<Article> {
    @Resource
    private ArticlesService articlesService;
    @Resource
    private CollectRecordService collectRecordService;
    @Resource
    private WxPlatformService wxPlatformService;
    @Resource
    private WxTokenService wxTokenService;

    @Resource
    private ArticleService articleService;

    @Resource
    private Environment env;

    @Override
    public BasicService<Article> getBasicService() throws Exception {
        return articlesService;
    }

    /**
     * 新增图文素材并同步至微信服务器
     *
     * @author lujiang
     * @date  2019/02/26 10:03
     * @param entitys 素材集合
     * @return
     */
    @RequestMapping(value = "/insertArticlesList", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public Map<String, Object> insertArticlesList(@RequestBody List<Article> entitys) {
        Map<String, Object> map = new HashMap<String, Object>(16);
        try {
            map = articlesService.insertArticlesList(entitys);
        } catch (Exception e) {
            map.put("success", false);
            map.put("msg",e.getMessage());
            LCLogger.withException(e);
        }
        return map;
    }

    /**
     * 修改永久图文
     *
     * @author lujiang
     * @date 2018-05
     * @param source
     * @param session
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    @Override
    public Map<String, Object> update(@JsonParam Article source, HttpSession session, HttpServletRequest request,
                                      HttpServletResponse response) {
        Map<String, Object> map = new HashMap<>(16);
        try {
            WxPlatform wxplatform = new WxPlatform();
            wxplatform.setId(source.getWxId());
            WxPlatform platform = wxPlatformService.queryById(wxplatform);
            List<Article> list = new ArrayList<>();
            list.add(source);
            map = articleService.updateArticles(platform.getWx_app_id(),list);

            if (StringUtils.equals(map.get("result").toString(),"1")) {
                articlesService.update(source);
            }
            map.put("success", true);
        } catch (Exception e) {
            map.put("success", false);
            LCLogger.withException(e);
        }

        return map;
    }

    /**
     * 批量修改图文
     *
     * @author lujiang
     * @date 2018-05
     * @param list 图文list
     * @param session
     * @param request
     * @param response
     * @return
     */
    @Override
    public Map<String, Object> batchUpsert(@RequestBody List<Article> list, HttpSession session,
                                           HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result  = new HashMap<>(16);
        try {
            result = articlesService.updateArticlesList(list);
            result.put("success", true);
        } catch (Exception e) {
            result.put("success", false);
            result.put("result", e.getMessage());
            LCLogger.withException(e);
        }
        return  result;
    }

    /**
     * 删除永久图文素材
     *
     * @author lujiang
     * @date  2019/02/26 10:03
     * @param entity 图文对象
     * @param session
     * @param request
     * @param response
     * @return map
     * @throws Exception
     */
    @RequestMapping(value = "/deleteById", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    @Override
    public Map<String, Object> deleteById(@JsonParam Article entity, HttpSession session, HttpServletRequest request,
                                          HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>(16);
        try {
            map = articlesService.deleteArticles(entity);
            map.put("success", true);
        } catch (Exception e) {
            map.put("success", false);
            map.put("result", e.getMessage());
            LCLogger.withException(e);
        }
        return map;
    }


    /**
     * 核销code 接口
     *
     * @author lujiang
     * @date 2018-5
     * @param code 卡券code
     * @param wxId 公众号信息id
     * @return
     */
    @RequestMapping(value = "/destroyCode", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> destroyCode(@JsonParam String code,@JsonParam  Long wxId) {
        Map<String, Object> map = new HashMap<>(16);
        //865903682697
        map.put("code", code);
        String accessToken;
        try {
            WxPlatform wxplatform = new WxPlatform();
            wxplatform.setId(wxId);
            WxPlatform platform = wxPlatformService.queryById(wxplatform);
            accessToken = wxTokenService.getWxAccessTokenByAppId(platform.getWx_app_id()).getAccess_token();
            String requestUrl = env.getProperty("weixinuri.destroyCodeUrl").replace("ACCESS_TOKEN", accessToken);
            Gson gson = new Gson();
            // 转换成特定格式字符串
            String data = gson.toJson(map);
            JSONObject result = WeixinHttpUtil.httpRequest(requestUrl, "POST", data);
            String zero = "0";
            String errcode = "errcode";
            if (zero.equals(result.get(errcode).toString())) {
                CollectRecord collectRe = new CollectRecord();
                collectRe.setWechatCode(code);
                collectRe.setPageFlag(false);
                List<CollectRecord> collectRecords = collectRecordService.queryByExamplePage(collectRe);
                for (int i = 0; i < collectRecords.size(); i++) {
                    collectRecords.get(i).setClaimStatus("Used");
                    collectRecordService.update(collectRecords.get(i));
                }
            }
            map.put("result", result);
        } catch (Exception e) {
            LCLogger.withException(e);
        }

        return map;

    }

    /**
     * 查询图文消息列表（多图文只显示第一条）
     *
     * @author lujiang
     * @date 2018-11
     * @param entity 图文消息对象
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/queryByArticlesByExamplePage", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> queryByArticlesByExamplePage(@JsonParam Article entity) throws Exception {
        Map<String, Object> result = new HashMap<>(16);
        try {
            List<Article> list = articlesService.queryByArticlesByExamplePage(entity);
            result.put("rows",list);
            result.put("total", articlesService.getCount(entity));
            result.put("success",true);
        } catch (Exception e) {
            result.put("success",false);
            result.put("msg",e.getMessage());
            LCLogger.withException(e);
        }
        return result;
    }

    /**
     * 根据OpenID列表群发
     *
     *
     * @author lujiang
     * @date 2018-11
     * @param articles
     * @return
     */
    @RequestMapping(value = "/sendArticles", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> sendArticles(@RequestBody Article articles) {
        Map<String, Object> result = new HashMap<>(8);
        try {
            result = articlesService.sendArticles(articles);
            result.put("msg","发送成功");
        } catch (Exception e) {
            result.put("success",false);
            result.put("msg",e.getMessage());
            LCLogger.withException(e);
        }
        return result;
    }

    /**
     * 群发图文客户筛选
     *
     * @author lujiang
     * @date 2019-2-21
     * @param qps
     * @param account
     * @return
     */
    @RequestMapping(value = "/queryAccountListByExamplePage", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> queryAccountListByExamplePage(@JsonParam QueryParams qps, @JsonParam Account account) {
        Map<String, Object> result = new HashMap<>(8);
        try {
            String order = qps.getOrder();
            account = (Account)BasicModel.transformClass(account, qps);
            account.setAttr1(order);
            result = articlesService.queryAccountListByExamplePage(account);
            result.put("success",true);
        } catch (Exception e) {
            result.put("success",false);
            result.put("msg",e.getMessage());
            LCLogger.withException(e);
        }
        return result;
    }

    /**
     * 查询图文详情
     *
     * @author lujiang
     * @date 2019-5-30 18:41
     * @param article 素材信息
     * @return
     */
    @RequestMapping(value = "/queryByGroupId")
    @ResponseBody
    public Map<String, Object> queryByGroupId(@RequestBody Article article) {
        Map<String, Object> result = new HashMap<>(4);
        try {
            List<Article> articleList = articlesService.queryByGroupId(article);
            result.put("result",articleList);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }
}
